package com.parktech.sun.web.controller.management.action;

import com.parktech.sun.domain.model.Constants;
import com.parktech.sun.domain.model.addressbook.ContactGroup;
import com.parktech.sun.domain.model.addressbook.ContactMember;
import com.parktech.sun.domain.model.email.Email;
import com.parktech.sun.domain.model.email.EmailTemplate;
import com.parktech.sun.domain.model.sunhz.Enterprise;
import com.parktech.sun.domain.repository.Page;
import com.parktech.sun.domain.service.sunhz.*;
import com.parktech.sun.utils.TreeJsModel;
import com.parktech.sun.utils.action.MailSender;
import com.parktech.sun.utils.action.SmtpConfig;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: guo
 * Date: 11-1-12
 * Time: 下午11:47
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/management/action")
public class EmailController {
    private final String redirectListURL = "redirect:listSuccessEmails";
    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    private EmailTemplateService emailTemplateService;
    @Autowired
    private EmailService emailService;
    @Autowired
    private ContactGroupService contactGroupService;
    @Autowired
    private ContactMemberService contactMemberService;
    @Autowired
    private EnterpriseService enterpriseService;

    @RequestMapping(value = "/listSuccessEmails", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView listSuccessEmails(HttpServletRequest request) {
        Integer currentPageNo = request.getParameter("pageNo") != null ? Integer.parseInt(request.getParameter("pageNo").trim()) : 1;
        ModelAndView modelAndView = new ModelAndView("management/email/emailSentList");
        List fieldColumns = new ArrayList();
        List searchValues = new ArrayList();
        fieldColumns.add("status");
        searchValues.add(Constants.ACTION_STATUS_SUCCESS);
        Page<Email> returnPage = new Page<Email>(Constants.PAGINATION_PAGE_SIZE, currentPageNo);
        returnPage.setTotalCount(emailService.getTotalSizeWithSimilarCondition(Email.class, fieldColumns, searchValues));
        returnPage.setResult(emailService.getPaginationObjectsWithSimilarCondition(Email.class, currentPageNo, Constants.PAGINATION_PAGE_SIZE, fieldColumns, searchValues, null, null));

        return modelAndView.addObject(returnPage);
    }


    @RequestMapping(value = "/manageSendEmail", method = RequestMethod.GET)
    public String manageSendEmail(Model model) {
        model.addAttribute(new Email());
        //  model.addAttribute("treeJsModelList",getTreeJsModelList());
        // ModelAndView modelAndView = new ModelAndView("management/email/emailSendAdd");
        //   return modelAndView.addObject("email", new Email());
        return "management/email/emailSendAdd";
    }

    @RequestMapping(value = "/saveManageSendEmail", method = RequestMethod.POST)
    public String saveManageSendEmail(@ModelAttribute Email email, Model model, HttpServletRequest request) throws InvocationTargetException, IllegalAccessException, ParseException {
        if(email.getSenderName()!=null&&email.getSenderName().indexOf("%")!=-1)
        {
            email.setSenderPassword(email.getSenderName().substring(email.getSenderName().indexOf("%")+1));
            email.setSenderName(email.getSenderName().substring(0,email.getSenderName().indexOf("%")));
        }
        List<String> contactMemberIDList = new ArrayList<String>();
        List<String> enterpriseIDList = new ArrayList<String>();
        List<String> outAcceptorEmailList = new ArrayList<String>();
        String contactMixStr = request.getParameter("contactMixStr");
        String outAcceptorEmailMix = request.getParameter("outAcceptorName");
        if (contactMixStr != null && (contactMixStr.indexOf("member_") != -1 || contactMixStr.indexOf("enterprise_") != -1)) {
            String[] contactMixStrArray = contactMixStr.split("#");
            for (String str : contactMixStrArray) {
                if (str != null && str.indexOf("member_") != -1 ) {
                    contactMemberIDList.add(str.substring(str.indexOf("member_") + 7));
                } else if (str != null && str.indexOf("enterprise_") != -1) {
                    enterpriseIDList.add(str.substring(str.indexOf("enterprise_") + 11));
                }
            }
        }
        ////////////////////////////////////////////////////////////////////////////////////////
        if (outAcceptorEmailMix != null && outAcceptorEmailMix.length() > 6) {
            String[] outAcceptorEmailArray = outAcceptorEmailMix.split(";");
            for (String outAcceptorEmail : outAcceptorEmailArray) {
                if (outAcceptorEmail != null && outAcceptorEmail.length() > 6 && outAcceptorEmail.indexOf("@")!=-1 )
                    outAcceptorEmailList.add(outAcceptorEmail);
            }
        }
        ///////////////////////////////////////////////////////////////////////////////////
        if (outAcceptorEmailList.size() != 0 && email != null) {
            if (!email.isScheduleSend()) {
                MailSender mailSender = new MailSender();
                for (String outAcceptorEmail : outAcceptorEmailList) {
                    Email newEmail = new Email();
                    BeanUtils.copyProperties(newEmail, email);
                    newEmail.setId(null);
                    newEmail.setAcceptorEmail(outAcceptorEmail);
                    boolean isSuccess = mailSender.send(outAcceptorEmail, email.getTopic(), email.getContent(), email.getSenderName(), email.getSenderPassword());
                    if (isSuccess && newEmail.isSaveHistory()) {
                        newEmail.setStatus(Constants.ACTION_STATUS_SUCCESS);
                        emailService.saveOrUpdateBean(newEmail);
                    }
                }
            } else {
                String scheduleSendDate = request.getParameter("scheduleSendDate");
                String scheduleSendHour = request.getParameter("scheduleSendHour");
                String scheduleSendMinute = request.getParameter("scheduleSendMinute");
                String scheduleSendDatetime = scheduleSendDate + " " + scheduleSendHour + ":" + scheduleSendMinute + ":00";
                email.setScheduleSendDatetime(dateFormat.parse(scheduleSendDatetime));
                for (String outAcceptorEmail : outAcceptorEmailList) {
                    Email newEmail = new Email();
                    BeanUtils.copyProperties(newEmail, email);
                    newEmail.setId(null);
                    newEmail.setAcceptorEmail(outAcceptorEmail);
                    emailService.saveOrUpdateBean(newEmail);
                }
            }
        }
        ////////////////////////////////////////////////////////////
        if (email != null && !email.isScheduleSend() && (contactMemberIDList.size() != 0 || enterpriseIDList.size() != 0)) {
            MailSender mailSender = new MailSender();
            for (String contactMemberID : contactMemberIDList) {
                ContactMember contactMember = contactMemberService.getBeanByID(Long.valueOf(contactMemberID));
                if (contactMember.getEmail() == null || contactMember.getEmail().indexOf("@")==-1 || contactMember.getEmail().length() < 6 )
                    continue;
                Email newEmail = new Email();
                BeanUtils.copyProperties(newEmail, email);
                newEmail.setId(null);
                newEmail.setAcceptorEmail(contactMember.getEmail());
                newEmail.setToAcceptor(contactMember);
                boolean isSuccess = mailSender.send(contactMember.getEmail(), email.getTopic(), email.getContent(), email.getSenderName(), email.getSenderPassword());
                if (isSuccess && newEmail.isSaveHistory()) {
                    newEmail.setStatus(Constants.ACTION_STATUS_SUCCESS);
                    emailService.saveOrUpdateBean(newEmail);
                }
            }
            for (String enterpriseID : enterpriseIDList) {
                Enterprise enterprise = enterpriseService.getBeanByID(Long.valueOf(enterpriseID));
                if (enterprise.getEmail() == null || enterprise.getEmail().indexOf("@")==-1 || enterprise.getEmail().length() < 6)
                    continue;
                Email newEmail = new Email();
                BeanUtils.copyProperties(newEmail, email);
                newEmail.setId(null);
                newEmail.setToAcceptor(enterprise);
                newEmail.setAcceptorEmail(enterprise.getEmail());
                boolean isSuccess = mailSender.send(enterprise.getEmail(), email.getTopic(), email.getContent(), email.getSenderName(), email.getSenderPassword());
                if (isSuccess && newEmail.isSaveHistory()) {
                    newEmail.setStatus(Constants.ACTION_STATUS_SUCCESS);
                    emailService.saveOrUpdateBean(newEmail);
                }
            }
            return redirectListURL;
        }
        /////////////////////////////////////////////////////////////////////
        if (email != null && email.isScheduleSend() && (contactMemberIDList.size() != 0 || enterpriseIDList.size() != 0)) {
            String scheduleSendDate = request.getParameter("scheduleSendDate");
            String scheduleSendHour = request.getParameter("scheduleSendHour");
            String scheduleSendMinute = request.getParameter("scheduleSendMinute");
            String scheduleSendDatetime = scheduleSendDate + " " + scheduleSendHour + ":" + scheduleSendMinute + ":00";
            email.setScheduleSendDatetime(dateFormat.parse(scheduleSendDatetime));
            for (String contactMemberID : contactMemberIDList) {
                ContactMember contactMember = contactMemberService.getBeanByID(Long.valueOf(contactMemberID));
                if (contactMember.getEmail() == null || contactMember.getEmail().indexOf("@")==-1 || contactMember.getEmail().length() < 6)
                    continue;
                Email newEmail = new Email();
                BeanUtils.copyProperties(newEmail, email);
                newEmail.setId(null);
                newEmail.setToAcceptor(contactMember);
                newEmail.setAcceptorEmail(contactMember.getEmail());
                emailService.saveOrUpdateBean(newEmail);
            }
            for (String enterpriseID : enterpriseIDList) {
                Enterprise enterprise = enterpriseService.getBeanByID(Long.valueOf(enterpriseID));
                if (enterprise.getEmail() == null || enterprise.getEmail().indexOf("@")==-1 || enterprise.getEmail().length() < 6)
                    continue;
                Email newEmail = new Email();
                BeanUtils.copyProperties(newEmail, email);
                newEmail.setId(null);
                newEmail.setAcceptorEmail(enterprise.getEmail());
                newEmail.setToAcceptor(enterprise);
                emailService.saveOrUpdateBean(newEmail);
            }
        }
        model.addAttribute(new Email());
        return "management/email/emailSendAdd";
    }

    /* @ModelAttribute("emailTemplateMap")
    public Map<String, String> getAllEmailTemplateMap() {
        Map<String, String> emailTemplateMap = new TreeMap<String, String>();
        emailTemplateMap.put("--请选择模板--","");
        List<EmailTemplate> emailTemplateList = emailTemplateService.getPaginationObjectsWithSimilarCondition(EmailTemplate.class, 1, 6666, null, null, null, null);
        for (EmailTemplate emailTemplate : emailTemplateList) {
            emailTemplateMap.put(emailTemplate.getName(), emailTemplate.getContent());
        }
        return emailTemplateMap;
    }*/

    @ModelAttribute("emailTemplateList")
    public List<EmailTemplate> getAllEmailTemplateList() {
        List<EmailTemplate> emailTemplateList = new ArrayList<EmailTemplate>();
        EmailTemplate emptyTemplate = new EmailTemplate();
        emptyTemplate.setName("--请选择模板--");
        emptyTemplate.setContent("");
        emailTemplateList.add(emptyTemplate);
        emailTemplateList.addAll(emailTemplateService.getPaginationObjectsWithSimilarCondition(EmailTemplate.class, 1, 6666, null, null, null, null));

        return emailTemplateList;
    }

    @RequestMapping(value = "/deleteSuccessEmails", method = RequestMethod.POST)
    public String deleteSuccessEmails(HttpServletRequest request) {
        String[] successEmailIDArray = request.getParameter("selectedSuccessEmailIDArray") == null ? new String[0] : request.getParameter("selectedSuccessEmailIDArray").trim().split(",");
        for (String successEmailID : successEmailIDArray) {
            emailService.removeBean(Long.valueOf(successEmailID.trim()));
        }
        return redirectListURL;
    }

    /*@ModelAttribute("contactGroupList")
    public List<ContactGroup> getAllContactGroupList() {
        return contactGroupService.getPaginationObjectsWithSimilarCondition(ContactGroup.class, 1, 666, null, null, null, null);
    }*/

    @ModelAttribute("emailSenderMap")
    public Map<String,String> getEmailSenderNameMap ()
    {
        Map<String,String> emailSenderMap = new LinkedHashMap();
        MailSender mailSender = new MailSender();
        SmtpConfig smtpConfig = mailSender.getSmtpConfig();
        emailSenderMap.put(smtpConfig.getUser()+"%"+smtpConfig.getPassword(),smtpConfig.getUser());
        emailSenderMap.put(smtpConfig.getUserName2()+"%"+smtpConfig.getPassword2(),smtpConfig.getUserName2());
        return emailSenderMap;
    }

    @ModelAttribute("treeJsModelList")
    public List<TreeJsModel> getTreeJsModelList() {
        List<TreeJsModel> treeJsModelList = new ArrayList<TreeJsModel>();
        List<ContactGroup> contactGroupList = contactGroupService.getPaginationObjectsWithSimilarCondition(ContactGroup.class, 1, 99999, null, null, null, null);
        for (ContactGroup contactGroup : contactGroupList) {
            TreeJsModel treeJsModel = new TreeJsModel();
            treeJsModel.setParentNodeID("0");
            treeJsModel.setCurrentNodeID("group_" + contactGroup.getId());
            treeJsModel.setCurrentNodeName(contactGroup.getName());
            treeJsModelList.add(treeJsModel);
            if (contactGroup.getContactMembers().size() != 0) {
                treeJsModel.setHaveChild(true);
                for (ContactMember contactMember : contactGroup.getContactMembers()) {
                    TreeJsModel subJsModel = new TreeJsModel();
                    subJsModel.setParentNodeID("group_" + contactGroup.getId());
                    subJsModel.setHaveChild(false);
                    subJsModel.setCurrentNodeID("member_" + contactMember.getId());
                    subJsModel.setCurrentNodeName(contactMember.getName());
                    treeJsModelList.add(subJsModel);
                }
            }
        }
        ///////////////////////////////////////////////////////////////////////
        List<Enterprise> enterpriseList = enterpriseService.getPaginationObjectsWithSimilarCondition(Enterprise.class, 1, 99999, null, null, null, null);
        TreeJsModel treeJsModel = new TreeJsModel();
        treeJsModel.setParentNodeID("0");
        treeJsModel.setCurrentNodeID("father_1");
        treeJsModel.setCurrentNodeName("企业机构");
        treeJsModelList.add(treeJsModel);
        treeJsModel.setHaveChild(true);
        for (Enterprise enterprise : enterpriseList) {
            TreeJsModel subJsModel = new TreeJsModel();
            subJsModel.setParentNodeID("father_1");
            subJsModel.setHaveChild(false);
            subJsModel.setCurrentNodeID("enterprise_" + enterprise.getId());
            subJsModel.setCurrentNodeName(enterprise.getName());
            treeJsModelList.add(subJsModel);
        }

        return treeJsModelList;
    }


}